// 管理后台路由初始化
const logger = require("../../utils/logger")
const mysqlUtil = require("../../utils/mysqlUtil")
const uuid = require('uuid')
const redisUtil = require("../../utils/redisUtil")
const userModule = require('./user')
const departmentModule = require('./department')
const positionModule = require('./position')

// 检查token
async function checkToken(ctx, next) {
    let token = ctx.headers.token;
    if (!token) return ctx.body = {code: 9999, message: 'missing token'};

    try {
        let userId = await redisUtil.get('OA:TOKEN:USER:' + token);
        if (!userId) return ctx.body = {code: 9999, message: '请重新登录'};
        let curToken = await redisUtil.get('OA:USER:TOKEN:' + userId);
        if (token != curToken) return ctx.body = {code: 9999, message: '请重新登录'};
        ctx.headers.userId = userId;
        // 刷新token持续时间
        redisUtil.client.expire('OA:TOKEN:USER' + token, 2 * 24 * 60 * 60);
        redisUtil.client.expire('OA:USER:TOKEN' + userId, 2 * 24 * 60 * 60);
        await next();
    }
    catch (err) {
        logger.error(err);
        ctx.body = {code: -1, message: 'system error'};
    }
}

// 用户登录
async function login(ctx) {
    let params = ctx.request.body
    if (!params.username || !params.password) return ctx.body = {code: -1, message: '参数缺失'}
    try {
        let sqlStr = 'SELECT id userId, nickname FROM tb_admin_user WHERE username = ? AND pwd = ? LIMIT 1'
        let res = await mysqlUtil.execute(sqlStr, [params.username, params.password])
        if (res.length == 0) return ctx.body = {code: -1, message: '用户名或密码错误'}
        let userId = res[0].userId
        let nickname = res[0].nickname
        let token = uuid.v4().replace(/-/g, '')
        redisUtil.set('OA:TOKEN:USER:' + token, userId, 'EX', 2 * 24 * 60 * 60);
        redisUtil.set('OA:USER:TOKEN:' + userId, token, 'EX', 2 * 24 * 60 * 60);
        ctx.body = {code: 0, message: 'success', data: {nickname, token}};
    } catch (err) {
        logger.error(err)
        ctx.body = {code: -1, message: 'system error'}
    }
}

// 用户登出
async function logout(ctx) {
    let token = ctx.headers.token;
    if (!token) return ctx.body = {code: 0, message: 'success'};

    try {
        let userId = await redisUtil.get('OA:TOKEN:USER:' + token);
        if (!userId) return ctx.body = {code: 0, message: 'success'};
        let curToken = await redisUtil.get('OA:USER:TOKEN:' + userId);
        if (token != curToken) return ctx.body = {code: 0, message: 'success'};
        redisUtil.del('OA:TOKEN:USER:' + token)
        redisUtil.del('OA:USER:TOKEN:' + userId)
        ctx.body = {code: 0, message: 'success'}
    } catch (err) {
        logger.error(err)
        ctx.body = {code: 0, message: 'success'}
    }
}

// 管理员信息
async function adminInfo(ctx) {
    let userId = ctx.headers.userId;
    if (!userId) return ctx.body = {code: -1, message: '参数缺失'};
    try {
        let sql = 'SELECT nickname FROM tb_admin_user WHERE id = ? LIMIT 1';
        let res = await mysqlUtil.execute(sql, [userId]);
        if (res.length == 0) return ctx.body = {code: -1, message: '用户不存在'};
        let nickname = res[0].nickname;
        let avatar = 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif';
        return ctx.body = {code: 0, message: 'success', data: {nickname, avatar}};
    }
    catch (err) {
        logger.error(err);
        ctx.body = {code: -1, message: 'system error'};
   }
}

// 获取岗位列表
async function positionList(ctx) {
    try {
        let res = await mysqlUtil.execute('SELECT * FROM con_position')
        ctx.body = {code: 0, message: 'success', data: res}
    } catch (err) {
        logger.error(err)
        ctx.body = {code: -1, message: 'system error'}
    }
}

function initAdmin(router) {

    // 登录
    router.post('/admin/login', login)

    // 登出
    router.post('/admin/logout', logout)

    // 获取管理员信息
    router.get('/admin/info', checkToken, adminInfo)

    // 员工列表
    router.get('/admin/userList', checkToken, userModule.userList)

    // 添加员工
    router.post('/admin/addUser', checkToken, userModule.addUser)

    // 修改员工密码
    router.post('/admin/modifyUserPwd', checkToken, userModule.modifyUserPwd)

    // 删除员工
    router.post('/admin/delUser', checkToken, userModule.delUser)

    // 从部门岗位中移除
    router.post('/admin/rmFromDp', checkToken, userModule.rmFromDp)

    // 更新岗位部门
    router.post('/admin/updateUserDp', checkToken, userModule.updateUserDp)

    // 增加部门岗位
    router.post('/admin/addUserDp', checkToken, userModule.addUserDp)

    // 更新员工信息
    router.post('/admin/updateUserInfo', checkToken, userModule.updateUserInfo)

    // 获取部门列表
    router.get('/admin/departmentList', checkToken, departmentModule.departmentList)

    // 添加部门
    router.post('/admin/addDepartment', checkToken, departmentModule.addDepartment)

    // 删除部门
    router.post('/admin/delDepartment', checkToken, departmentModule.delDepartment)

    // 更新部门排序
    router.post('/admin/updateDepartmentSort', checkToken, departmentModule.updateDepartmentSort)

    // 获取岗位列表
    router.get('/admin/positionList', checkToken, positionModule.positionList)

    // 添加岗位
    router.post('/admin/addPosition', checkToken, positionModule.addPosition)

    // 删除岗位
    router.post('/admin/delPosition', checkToken, positionModule.delPosition)

    // 更新岗位排序
    router.post('/admin/updatePositionSort', checkToken, positionModule.updatePositionSort)
}

module.exports = {
    initAdmin
}